package com.example.demo.handler;

import org.springframework.web.bind.annotation.RestController;

import com.example.demo.service.PlatformUserService;
import com.example.demo.util.RegexUtil;
import com.woniuxy.movice.entity.PlatformUser;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api("登录")
@RestController
@RequestMapping("/user")
public class LoginController {
	
	@Autowired
	private RedisTemplate<Object,Object> redisTemplate;
	
	@Resource
	private PlatformUserService platformUserService;
	    
	@RequestMapping("/test")
	public String test(HttpServletRequest request){
		PlatformUser user = new PlatformUser();
		PlatformUser user1 = new PlatformUser();
		user.setAccount("dsafds");
		user1.setAccount("dsafds");
		request.getSession().setAttribute("user:"+request.getSession().getId(), user);
		request.getSession().setAttribute("user:hhhhh",user1);
		return request.getSession().getId();
	}
	
	
	//登录
	@RequestMapping(value="/login")
	@ApiOperation(value="登录",notes="返回登录结果，输入(String) account,(String) pass, (String) code")
	public String login(HttpServletRequest request,String account,String pass,String code){
		System.out.println(account + pass + code);
		String result="登录成功";
		//格式检查
		if(!account.matches(RegexUtil.REGEX_MOBILE) || !pass.matches(RegexUtil.REGEX_PASSWORD)){
			result="账号或密码格式错误";
			return result;
		}
		//验证码
		Object obj = request.getSession().getAttribute("loginCode");
		//移除验证码
		request.getSession().removeAttribute("loginCode"+request.getSession().getId());
		if(obj==null){
			return result;
		}
		String realCode=(String) obj;
		if(!realCode.equalsIgnoreCase(code)){
			result="验证码有误";
		}
		//调用Service处理业务逻辑
		result=platformUserService.login(account,pass);
		if(result.contains("成功")){
			System.out.println(redisTemplate);
            request.getSession().setAttribute("loginUser", account);
            System.out.println("account:"+account);
		}
		return result;
	}
	
	//注销
	@RequestMapping(value="/logout" ,method=RequestMethod.GET)
	@ApiOperation(value="登出",notes="回到登录页面")
	public void loginOut(HttpServletRequest request,HttpServletResponse response){
		request.getSession().removeAttribute("account");
		try {
			response.sendRedirect("/html/login.html");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
